<template>
  <div class="videoContainer" :style="{display:style}">
    <video autoplay ref="remoteVideo" :style="{display:style}" muted="false">您的浏览器不支持 video 标签。</video>
  </div>
</template>

<script setup>
import { inject, onMounted, onUnmounted, ref } from "vue";
import { useWebsocket } from "../hooks";
import store from "@/store";
import adapter from "webrtc-adapter";

const socket = useWebsocket(handelMessage); //连接socket
const style = ref('block'); //设置视频是否显示
const userData = store.state.userData
const roomData = store.state.roomData

//视频连接相关
const localVideo = ref(null)  //本地视频流
const remoteVideo = ref(null); //对方的视频流
const peerConnection = ref(null);
const peerConnectionConfig = {  
  iceServers: [  
    {  
      urls: 'stun:stun.l.google.com:19302'  
    }  
  ]  
};

async function video() {
  //如果是房主的话就不用视频
  if(store.state.roomData.userId == store.state.userData.userId){
    style.value = 'none'
  }
  //socket
  if(!socket){
    //检验socket是否出错
    socket.onerror = (error) => console.error("WebSocket错误:", error);
  }
  
  peerConnection.value = new RTCPeerConnection(peerConnectionConfig);  
  peerConnection.value.ontrack = (event) => {  
    remoteVideo.value.srcObject = event.streams[0];  
  }; 
  const stream = await getLocalStream();
  localVideo.value = stream;  
  stream.getTracks().forEach((track) => peerConnection.value.addTrack(track, stream));  

  //生成offer
  const offer = await peerConnection.value.createOffer();
  console.log('生成offer',offer)  
  await peerConnection.value.setLocalDescription(offer);  
  socket.send(JSON.stringify({ 
    type:'offer', 
    offer:offer, 
    userId : userData.userId, 
    roomId : roomData.roomId
  }));  
}

//接收socket的信息
async function handelMessage(event) {
  const data = JSON.parse(event.data);  
  //防止用户重复收到消息
  if(userData.userId == data.userId){
    return;
  }
  console.log('socket发送的'+ data.type , data);

  const peer = peerConnection.value; 
  //看人下菜碟
  switch (data.type) {  
    case 'offer':  
      await peer.setRemoteDescription(new RTCSessionDescription(data.offer))
      const answer = await peer.createAnswer();  
      console.log('生成answer',answer)
      await peer.setLocalDescription(answer);  
      socket.send(JSON.stringify({ 
        type: 'answer', 
        answer: answer, 
        userId:userData.userId,
        roomId:roomData.roomId
      }));  
      break;  
    case 'answer':  
      peer.setRemoteDescription(new RTCSessionDescription(data.answer));  
      break;  
    case 'candidate':  
      const candidate = new RTCIceCandidate(data.candidate);  
      peer.addIceCandidate(candidate);  
      break;  
    }  
}

onMounted(async () => {
  // 初始化peerConnection并监听必要的事件  
  peerConnection.value = new RTCPeerConnection(peerConnectionConfig);  
  peerConnection.value.onicecandidate = (event) => {  
    if (event.candidate) {
      socket.send(JSON.stringify({ 
        type: 'candidate',
        candidate: event.candidate ,
        userId:userData.userId, 
        roomId:roomData.roomId
      }));  
    }
  };
});

// 获取本地音视频流
async function getLocalStream() {
  // 获取视频流（屏幕共享）
  // const videoStream = await navigator.mediaDevices.getDisplayMedia({
  //   video: true,
  // });
  // 获取音频流
  const stream = await navigator.mediaDevices.getUserMedia({
    audio: true,
  });
  // 合成一个新的MediaStream对象
  // let stream = new MediaStream([
  //   ...videoStream.getTracks(),
  //   ...audioStream.getTracks(),
  // ]);
  // console.log(stream);
  if (checkMediaStream(stream)) {
    remoteVideo.value.srcObject = stream;
    return stream;
  }
}

//检验音视频流是否好用
async function checkMediaStream(stream) {
  if (!stream || !stream.getTracks) {
    console.error("No media stream or getTracks method not available");
    return false;
  }
  const tracks = stream.getTracks();
  let hasActiveVideoTrack = false;
  for (const track of tracks) {
    if (track.kind === "video" && track.readyState === "live") {
      hasActiveVideoTrack = true;
      break;
    }
  }
  if (hasActiveVideoTrack) {
    console.log("Media stream contains an active video track.");
    return true;
  } else {
    console.error("Media stream does not contain an active video track.");
    return false;
  }
}

//挂断
function hangUp() {  
  if (peerConnection.value) {  
    peerConnection.value.close();  
    peerConnection.value = null;  
  }  
  if (socket) {  
    socket.close();  
    socket = null;  
  }  
}

//暴露video方法
defineExpose({
  video,
  hangUp,
});

// 清理函数，在组件卸载时调用
onUnmounted(() => {
  hangUp();
});
</script>

<style scoped>
video {
  overflow: hidden;
  display: block;
  position: absolute;  
  top: 50%;  
  left: 50%;  
  transform: translate(-50%, -50%); /* 将视频的中心点移动到容器中心 */  
  height: 100%; /* 视频高度等于容器高度 */  
  width: auto; /* 视频宽度自适应 */  
}

template{
  height: 100%;  
  margin: 0;  
  display: flex;  
  justify-content: center; /* 水平居中 */  
  align-items: center; /* 垂直居中 */   
}

.videoContainer{
  position: relative; /* 为了子元素（视频）定位 */   
  top: 5rem; 
  height: 34rem; /* 设置视频容器的高度 */  
  width: 100%; /* 宽度自适应 */  
  max-width: 100%; /* 防止视频过宽 */  
  overflow: hidden; /* 隐藏超出容器的视频部分 */  
}
</style>